import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_xxyk/constant/routes.dart';
import 'package:flutter_xxyk/model/product.dart';
import 'package:flutter_xxyk/widgets/keep_alive.dart';
import 'package:flutter_xxyk/widgets/lesson.dart';
import 'package:get_it/get_it.dart';

class TabData {
  TabData({required this.label, required this.dataType});

  String label;

  String dataType;
}

class SubscriptionPage extends StatefulWidget {
  const SubscriptionPage({Key? key}) : super(key: key);

  @override
  _SubscriptionPageState createState() => _SubscriptionPageState();
}

class _SubscriptionPageState extends State<SubscriptionPage> {
  @override
  Widget build(BuildContext context) {
    List<TabData> tabDataList = [
      TabData(label: "图文", dataType: "article"),
      TabData(label: "音频", dataType: "audio"),
      TabData(label: "视频", dataType: "video"),
      TabData(label: "专栏", dataType: "column"),
      TabData(label: "课程", dataType: "course"),
      TabData(label: "直播", dataType: "alive"),
    ];
    return DefaultTabController(
      length: tabDataList.length,
      child: Scaffold(
        appBar: AppBar(
          toolbarHeight: 0,
          backgroundColor: Colors.white,
          bottom: TabBar(
            labelColor: Colors.black,
            labelStyle: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
            unselectedLabelStyle: TextStyle(
              fontWeight: FontWeight.normal,
            ),
            indicatorWeight: 3,
            isScrollable: true,
            tabs: tabDataList.map((t) => Tab(text: t.label)).toList(),
          ),
        ),
        body: TabBarView(
          children: _buildTabViews(tabDataList),
        ),
      ),
    );
  }

  List<Widget> _buildTabViews(List<TabData> dataList) {
    return dataList
        .map((data) => KeepAliveWrapper(
                child: CustomTabPage(
              type: data.dataType,
              label: data.label,
            )))
        .toList();
  }
}

class CustomTabPage extends StatefulWidget {
  CustomTabPage({Key? key, required this.type, required this.label}) : super(key: key);

  final String type;

  final String label;

  @override
  _CustomTabPageState createState() => _CustomTabPageState();
}

class _CustomTabPageState extends State<CustomTabPage> {
  final Dio dio = GetIt.I<Dio>();

  bool _isLoading = true;

  int _currentPage = 1;

  List<Product>? dataList;

  @override
  void initState() {
    getDataList();
    super.initState();
  }

  Future<void> getDataList() async {
    _isLoading = true;
    final res = await dio.get("/h5/product/${widget.type}/page", queryParameters: {
      "current": _currentPage,
      "size": 10,
    });
    final records = res.data["data"]["records"] as List;
    final products = records.map((r) => Product.fromJson(r)).toList();
    setState(() {
      dataList = products;
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return _isLoading
        ? Center(
            child: SpinKitPulse(
              color: Theme.of(context).colorScheme.secondary,
              size: 50.0,
            ),
          )
        : ListView.builder(
            itemCount: dataList!.length,
            itemBuilder: (context, index) {
              final data = dataList![index];
              return Ink(
                color: Colors.white,
                child: InkWell(
                  onTap: () {
                    if (widget.type == 'column') {
                      Navigator.of(context).pushNamed(AppRoutes.COLUMN_DETAIL, arguments: data.productId);
                    }
                  },
                  child: Container(
                    padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                    height: 114,
                    child: Row(
                      children: [
                        LessonPic(
                          imgUrl: data.imgUrl!,
                          label: widget.label,
                          imgWidth: MediaQuery.of(context).size.width * 3 / 7,
                        ),
                        Expanded(
                          child: Padding(
                            padding: EdgeInsets.only(left: 10),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  "${data.title}",
                                  maxLines: 3,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(fontWeight: FontWeight.bold, color: Color(0xff333333)),
                                ),
                                Text(
                                  "课时${data.resourceCnt}",
                                  style: TextStyle(fontSize: 12, color: Color(0xff9f9f9f)),
                                )
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              );
            });
  }
}
